package tjx.Listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;
import java.util.Hashtable;
import java.util.Map;

@WebListener()
public class OnlineListener implements HttpSessionListener {


    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        HttpSession session=httpSessionEvent.getSession();
        ServletContext application=session.getServletContext();
        String sessionId=session.getId();
        if(session.isNew())
        {
            String user=(String)session.getAttribute("user");
            user=(user==null)?"游客":user;
            Map<String,String>online=(Map<String, String>)application.getAttribute("online");
            if (online==null)
            {
                online=new Hashtable<String, String>();
            }
            online.put(sessionId,user);
            application.setAttribute("online",online);
        }
    }

    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session=httpSessionEvent.getSession();
        ServletContext application=session.getServletContext();
        String sessionId=session.getId();
        Map<String,String>online=(Map<String, String>)application.getAttribute("online");

            if (online!=null)
            {
                online.remove(sessionId);
            }
            application.setAttribute("online",online);
        }
    }
